package com.xoa.service.knowledge.impl;

import com.xoa.controller.enclosure.EnclosureController;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.dao.knowledge.KnowledgeColumnMapper;
import com.xoa.dao.knowledge.KnowledgeCustomerMapper;
import com.xoa.dao.knowledge.KnowledgeCustomerUselogMapper;
import com.xoa.dao.knowledge.KnowledgeDocfileMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.knowledge.*;
import com.xoa.model.users.Users;
import com.xoa.service.equipment.EquipmentService;
import com.xoa.service.knowledge.KnowlidgeService;
import com.xoa.service.knowledge.SubscribeService;
import com.xoa.service.knowledge.util.KnowledgeUtil;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateFormat;
import com.xoa.util.LimsJson;
import com.xoa.util.common.DataTree;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class KnowlidgeServiceImpl implements KnowlidgeService {

    @Autowired
    private KnowledgeColumnMapper knowledgeColumnMapper;

    @Autowired
    private KnowledgeDocfileMapper knowledgeDocfileMapper;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private AttachmentMapper attachmentMapper;

    @Autowired
    private EnclosureController enclosureController;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private KnowledgeCustomerMapper knowledgeCustomerMapper;

    @Autowired
    private SubscribeService subscribeService;

    private KnowledgeUtil knowUtil = null;

    @Autowired
    private KnowledgeCustomerUselogMapper knowledgeCustomerUselogMapper;

    /**
     * @Author: ZhuYize
     * @Date: 2020/9/12 16:26
     * @Description: 获取栏目分类
     * @param: parentColumnId 父id
     * @return: LimsJson
     */
    @Override
    public LimsJson getKnowledgeType(Integer parentColumnId,String colunmType) {
        LimsJson limsJson = new LimsJson<>(1, "查询失败");
        List<KnowledgeColumn> knowledgeColumnList = new ArrayList<>(); //返回结果集
        if (parentColumnId == null) {
            limsJson.setFlag(1);
            limsJson.setMsg("查询失败，请选择需要查看的栏目类型");
        } else {
            try {
                // 通过父id查询数据
                knowledgeColumnList = knowledgeColumnMapper.selectByColumnTypeAndPid(colunmType,parentColumnId);
            } catch (Exception e) {
                limsJson.setFlag(1);
                limsJson.setMsg("查询失败，程序出现问题，请联系管理员");
                e.printStackTrace();
            }
        }
        if (knowledgeColumnList!=null && knowledgeColumnList.size() > 0) {
            // 判断是否有子集
            for (KnowledgeColumn knowledgeColumn : knowledgeColumnList) {
                if(knowledgeColumn.getParentColumnId()!=null&&knowledgeColumn.getParentColumnId()==0){  //说明是二级分类，他的上一级是sysCode表
                    if(knowledgeColumn.getColumnType()!=null){
                        SysCode sysCode = sysCodeMapper.getSingleCode("KNOWLEDGE_COLUMN_TYPE",knowledgeColumn.getColumnType());
                        if(sysCode!=null){
                            knowledgeColumn.setColumnTypeName(sysCode.getCodeName());
                            knowledgeColumn.setParentColumnIdName(sysCode.getCodeName());
                        }
                    }
                }else{
                    KnowledgeColumn parentKnow =  knowledgeColumnMapper.selectByPrimaryKey(knowledgeColumn.getParentColumnId());
                    if(parentKnow!=null){
                        knowledgeColumn.setParentColumnIdName(parentKnow.getColumnName());
                    }
                    SysCode sysCode = sysCodeMapper.getSingleCode("KNOWLEDGE_COLUMN_TYPE",knowledgeColumn.getColumnType());
                    if(sysCode!=null){
                        knowledgeColumn.setColumnTypeName(sysCode.getCodeName());
                    }
                }
                List<KnowledgeColumn> columnList = knowledgeColumnMapper.selectByParentColumnId(knowledgeColumn.getColumnId());
                knowledgeColumn.setId(knowledgeColumn.getColumnId());
                knowledgeColumn.setName(knowledgeColumn.getColumnName());
                knowledgeColumn.setLabel(knowledgeColumn.getColumnName());
                if (columnList.size() > 0) {
                    knowledgeColumn.setIsLeaf(false);
                }
            }
            limsJson.setData(knowledgeColumnList);
            limsJson.setCode(0);
            limsJson.setFlag(0);
            limsJson.setMsg("查询成功");
        } else {
            limsJson.setFlag(1);
            limsJson.setMsg("无数据");
        }
        return limsJson;
    }

    @Override
    public LimsJson getKnowledgeTypeByCode(String codeNo) {
        LimsJson limsJson = new LimsJson<>(1, "查询失败");
        List<KnowledgeColumn> knowledgeColumnList = new ArrayList<>(); //返回结果集
        if (codeNo == null) {
            limsJson.setFlag(1);
            limsJson.setMsg("查询失败，请选择需要查看的栏目类型");
        } else {
            SysCode sysCode = sysCodeMapper.getSingleCode("KNOWLEDGE_COLUMN_TYPE",codeNo);
            if(sysCode!=null){
                limsJson.setObj(sysCode);
            }else{
                limsJson.setMsg("暂无数据");
            }
        }
        return limsJson;
    }

    @Override
    public LimsJson getColumnById(String columnIds) {
        LimsJson limsJson = new LimsJson<>(1, "查询失败");
        List<KnowledgeColumn> resultList = new ArrayList<>();
        if (columnIds == null) {
            limsJson.setFlag(1);
            limsJson.setMsg("查询失败，请选择需要查看的栏目类型");
        } else {
            if(!StringUtils.checkNull(columnIds)){
                resultList = getAll(columnIds);
                if(resultList!=null&&resultList.size()>0){
                    limsJson.setCode(0);
                    limsJson.setData(resultList);
                }else{
                    limsJson.setCode(0);
                    limsJson.setMsg("暂无数据");
                }
            }else{
                limsJson.setMsg("您没有知识类别权限");
            }
        }
        return limsJson;
    }


    /**
     * @Author: ZhuYize
     * @Date: 2020/9/12 17:20
     * @Description: 删除栏目类型
     * @param: columnIds 栏目类型id串
     * @return: LimsJson
     */
    @Override
    public LimsJson delKnowledgeType(String columnIds) {
        LimsJson limsJson = new LimsJson<>(1, "删除失败");
        if (columnIds == null || ("").equals(columnIds)) {
            limsJson.setFlag(1);
            limsJson.setMsg("删除失败，请选择需要删除的栏目类型");
        } else {
            try {
                String[] ids = columnIds.split(",");
                // 通过父ids查询数据
                List<KnowledgeColumn> knowledgeColumnList = knowledgeColumnMapper.selectByParentColumnIds(ids);
                if (knowledgeColumnList.size() > 0) {
                    limsJson.setFlag(1);
                    limsJson.setMsg("所选栏目类型下存在子类型，不能删除");
                } else {
                    // 通过栏目类型ids查询文件
                    List<KnowledgeDocfile> knowledgeDocfileList = knowledgeDocfileMapper.selectByColumnIds(ids);
                    if (knowledgeDocfileList.size() > 0) {
                        limsJson.setFlag(1);
                        limsJson.setMsg("所选栏目类型下存在文档，不能删除");
                    } else {
                        // 通过主键id批量删除
                        int result = knowledgeColumnMapper.deleteByColumnIds(ids);
                        if (result > 0) {
                            limsJson.setFlag(0);
                            limsJson.setCode(0);
                            limsJson.setMsg("删除成功");
                        } else {
                            limsJson.setFlag(1);
                            limsJson.setMsg("删除失败");
                        }
                    }
                }
            } catch (Exception e) {
                limsJson.setFlag(1);
                limsJson.setMsg("删除失败，程序出现问题，请联系开发人员");
                e.printStackTrace();
            }
        }
        return limsJson;
    }

    /**
     * 查询sys_code中的PARENT_NO=KNOWLEDGE_COLUMN_TYPE（知识栏目类别）
     * @param request
     * @return
     */
    @Override
    public LimsJson getColumnTag(HttpServletRequest request) {
        LimsJson limsJson = new LimsJson<>(1, "查询失败");
        List<KnowledgeColumn> resultList = new ArrayList<>(); //定义返回值
        List<SysCode> sysCodeList = sysCodeMapper.getSysCode("KNOWLEDGE_COLUMN_TYPE");
        for(SysCode sc : sysCodeList){
            KnowledgeColumn kc = new KnowledgeColumn();
            List<KnowledgeColumn> columnList = knowledgeColumnMapper.selectByColumnTypeAndPid(sc.getCodeNo(),0); //查询有无子集
            kc.setColumnType(sc.getCodeNo());
            kc.setName(sc.getCodeName());
            kc.setLabel(sc.getCodeName());
            if (columnList.size() > 0) {
                kc.setIsLeaf(false);
            }
            kc.setSysCode(true);  //标识是否是sysCode的数据
            resultList.add(kc);
        }
        if(resultList!=null&&resultList.size()>0) {
            limsJson.setData(resultList);
            limsJson.setCode(0);
            limsJson.setFlag(0);
            limsJson.setMsg("查询成功");
        }else {
            limsJson.setFlag(1);
            limsJson.setMsg("无数据");
        }
        return limsJson;
    }


    @Override
    public LimsJson childTree(HttpServletRequest request, String codeNo) {
        LimsJson limsJson = new LimsJson<>(1, "查询失败");
        List<Integer> dispIdList = new ArrayList<>();//定义前端不能选择的数据的id
        List<SysCode> sysCodeList = new ArrayList<>();
        List<KnowledgeColumn> resultList = new ArrayList<>(); //定义返回值
        if(StringUtils.checkNull(codeNo)||"null".equals(codeNo)){
            sysCodeList = sysCodeMapper.getSysCode("KNOWLEDGE_COLUMN_TYPE");
        }else{
            SysCode sysCode = sysCodeMapper.getSingleCode("KNOWLEDGE_COLUMN_TYPE",codeNo);
            sysCodeList.add(sysCode);
        }
        for(SysCode sc : sysCodeList){
            //ClumnTree dt = new ClumnTree();
            KnowledgeColumn kc = new KnowledgeColumn();
            //List<KnowledgeColumn> columnList = knowledgeColumnMapper.selectByColumnTypeAndPid(sc.getCodeNo(),0); //查询有无子集
            kc.setId(sc.getCodeId());
            kc.setLabel(sc.getCodeName());
            kc.setColumnType(sc.getCodeNo());
            dispIdList.add(sc.getCodeId());
            kc.setSysCode(true);  //标识是否是sysCode的数据
            kc.setName(sc.getCodeName());
//            if (columnList.size() > 0) {
//                kc.setIsLeaf(false);
//            }
            resultList.add(kc);
        }
        if(resultList!=null&&resultList.size()>0) {
            for(KnowledgeColumn ct : resultList){
                ct.setChildren(saveDataTree(ct));
            }
        }
        if(resultList!=null&&resultList.size()>0){
            limsJson.setCode(0);
            limsJson.setData(resultList);
            limsJson.setObj(dispIdList);
        }else{
            limsJson.setCode(0);
            limsJson.setMsg("暂无数据");
        }
        return limsJson;
    }

    List<KnowledgeColumn> saveDataTree(KnowledgeColumn dataTrees){
        List<KnowledgeColumn> resuTree = new ArrayList<>();
        List<KnowledgeColumn> columnList = new ArrayList<>();
        if(dataTrees.isSysCode()){
             columnList = knowledgeColumnMapper.selectByColumnTypeAndPid(dataTrees.getColumnType(),0); //查询有无子集
        }else{
            columnList = knowledgeColumnMapper.selectByParentColumnId(dataTrees.getId());
        }
        if(columnList!=null&&columnList.size()>0){
            for(KnowledgeColumn kc : columnList){
                kc.setName(kc.getColumnName());
                kc.setLabel(kc.getColumnName());
                kc.setId(kc.getColumnId());
//                ClumnTree dt = new ClumnTree();
//                dt.setId(kc.getColumnId());
//                dt.setCodeNo(kc.getColumnType());
//                dt.setSysCode(false);  //标识是否是sysCode的数据
//                dt.setName(kc.getColumnName());
                if(kc.isSysCode()){
                    List<KnowledgeColumn> cLi = knowledgeColumnMapper.selectByColumnTypeAndPid(kc.getColumnType(),0); //查询有无子集
                    if(cLi.size()>0){
                        kc.setIsLeaf(false);
                    }else{
                        kc.setIsLeaf(true);
                    }
                }else{
                    List<KnowledgeColumn> cLi =  knowledgeColumnMapper.selectByParentColumnId(kc.getId());
                    if(cLi.size()>0){
                        kc.setIsLeaf(false);
                    }else{
                        kc.setIsLeaf(true);
                    }
                }
                List<KnowledgeColumn> child = saveDataTree(kc);
                if(child.size()>0){
                    kc.setChildren(child);
                }
                resuTree.add(kc);
            }

        }
        dataTrees.setChildren(resuTree);
        return resuTree;
    }

    public LimsJson loging(HttpServletRequest request,String account,String password){
        LimsJson limsJson = new LimsJson<>(1, "登录失败");
        if(StringUtils.checkNull(account)||StringUtils.checkNull(password)){
            limsJson.setMsg("账号或密码不能为空");
        }else{
            KnowledgeCustomer customer = knowledgeCustomerMapper.selectByAccount(account);
            if(customer!=null){
                if(password.equals(customer.getLogingPassword())){
                    String privType = customer.getPrivType(); //获取该客户下载权限
                    String colunms = customer.getColumnId();  //获取该客户栏目类别，没有栏目类别也就没有下载查看权限
                    if(!StringUtils.checkNull(privType)&&!StringUtils.checkNull(colunms)){
                        if("1".equals(privType)){ //下载和浏览权限
                            //此处验证权限过期问题
                            if(customer.getDownloadBDate()!=null&&customer.getDownloadEDate()!=null){
                                if(knowUtil==null){
                                    knowUtil = new KnowledgeUtil();
                                }
                                //判断下载时间
                                boolean downFlag1 = knowUtil.belongCalendar(new Date(),customer.getDownloadBDate(),customer.getDownloadEDate()); //判断当前时间是否在下载时间内
                                //判断浏览时间，有下载权限就可以浏览
                                boolean downFlag2 = knowUtil.belongCalendar(new Date(),customer.getBrowseBDate(),customer.getBrowseEDate()); //判断当前时间是否在下载时间内
                                if(downFlag1||downFlag2){
                                    request.getSession().setAttribute("cust",customer.getCustomerId());
                                    limsJson.setCode(0);
                                    limsJson.setMsg("登录成功");
                                }else{
                                    limsJson.setMsg("您的下载权限已过期或还未开始。开始下载时间："+ DateFormat.getStrDate(customer.getDownloadBDate())+"结束下载时间："+DateFormat.getStrDate(customer.getDownloadEDate()));
                                }
                            }else{
                                limsJson.setMsg("您没有下载或浏览权限，请联系管理员");
                            }
                        }else if("0".equals(privType)){ //浏览权限
                            //此处验证权限过期问题
                            if(customer.getBrowseBDate()!=null&&customer.getBrowseEDate()!=null){
                                if(knowUtil==null){
                                    knowUtil = new KnowledgeUtil();
                                }
                                boolean downFlag = knowUtil.belongCalendar(new Date(),customer.getBrowseBDate(),customer.getBrowseEDate()); //判断当前时间是否在下载时间内
                                if(downFlag){
                                    request.getSession().setAttribute("cust",customer.getCustomerId());
                                    limsJson.setCode(0);
                                    limsJson.setMsg("登录成功");
                                }else{
                                    limsJson.setMsg("您的浏览权限已过期或还未开始。开始浏览时间："+ DateFormat.getStrDate(customer.getBrowseBDate())+"结束浏览时间："+DateFormat.getStrDate(customer.getBrowseEDate()));
                                }
                            }else{
                                limsJson.setMsg("您的浏览权限错误，请联系管理员");
                            }
                        }else{
                            limsJson.setMsg("您的权限错误，请联系管理员");
                        }
                    }else{
                        limsJson.setMsg("您无权查看或下载");
                    }
                }else{
                    limsJson.setMsg("账号或密码错误");
                }
            }else{
                limsJson.setMsg("用户不存在");
            }
        }
        return limsJson;
    }

    public void download(HttpServletRequest request, HttpServletResponse response, Integer docId){
        LimsJson limsJson = new LimsJson<>(1, "未知错误");
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        if(users!=null){
            KnowledgeCustomer customer = knowledgeCustomerMapper.selectByUserId(users.getUserId());
            if(customer!=null){
                String privType = customer.getPrivType(); //获取该客户下载权限
                String colunms = customer.getColumnId();  //获取该客户栏目类别
                if(!StringUtils.checkNull(privType)&&!StringUtils.checkNull(colunms)){
                    if("1".equals(privType)){ //下载和浏览权限
                        //此处验证权限过期问题
                        if(customer.getDownloadBDate()!=null&&customer.getDownloadEDate()!=null){
                            if(knowUtil==null){
                                knowUtil = new KnowledgeUtil();
                            }
                            boolean downFlag = knowUtil.belongCalendar(new Date(),customer.getDownloadBDate(),customer.getDownloadEDate()); //判断当前时间是否在下载时间内
                            if(downFlag){
                                if(docId!=null){
                                    KnowledgeDocfile kd = knowledgeDocfileMapper.selectByPrimaryKey(docId);
                                    //KnowledgeDocfile kd = knowledgeDocfileMapper.selectByAddress(key);
                                    if(kd!=null){
                                        if(kd.getColumnId()!=null){
                                            //此处验证该文档的栏目类别是否在客户栏目类别中
                                            boolean columnTypeFlag = isHaveColumn(colunms,kd.getColumnId());
                                            if(columnTypeFlag){
                                                String attachId = kd.getAttachmentId();
                                                if(!StringUtils.checkNull(attachId)){
                                                    String sqlType = (String) request.getSession().getAttribute(
                                                            "loginDateSouse");
                                                    if(StringUtils.checkNull(sqlType)){
                                                        sqlType="xoa1001";
                                                    }else{
                                                        sqlType="xoa" +sqlType;
                                                    }
                                                    String aid=attachId.split("@")[0];
                                                    Attachment attachment =attachmentMapper.selectByPrimaryKey(Integer.parseInt(aid));
                                                    if(attachment!=null){
                                                        try {
                                                            //文档下载时，新增下载记录
                                                            KnowledgeCustomerUselog kcu = new KnowledgeCustomerUselog();
                                                            kcu.setUserId(users.getUserId());
                                                            kcu.setUseType("1");
                                                            kcu.setDocfileId(docId);
                                                            kcu.setUseTime(new Date());
                                                            kcu.setCustomerName(customer.getCompanyName());
                                                            kcu.setDocfileName(kd.getDocfileName());
                                                            kcu.setDocfileNo(kd.getDocfileNo());
                                                            knowledgeCustomerUselogMapper.insertSelective(kcu);
                                                            enclosureController.download(attachment.getAid(),"knowledge",attachment.getYm(),attachment.getAttachId(),sqlType,null,response,request);
                                                        } catch (Exception e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                }
                                            }else{
                                                try {
                                                    //（2）显示弹窗并且当关闭弹窗后跳到指定页面
                                                    response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
                                                    response.getWriter().print("<html><body><script type='text/javascript'>alert('您无权下载此类型文档！');window.location='/knowledge/download';</script></body></html>");
                                                    //response.getWriter().close();
                                                    response.getWriter().flush();
                                                }catch (Exception e){
                                                    e.printStackTrace();
                                                }
                                            }
                                        }else{
                                            try {
                                                //（2）显示弹窗并且当关闭弹窗后跳到指定页面
                                                response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
                                                response.getWriter().print("<html><body><script type='text/javascript'>alert('文档类别错误错误！');window.location='/knowledge/download';</script></body></html>");
                                                //response.getWriter().close();
                                                response.getWriter().flush();
                                            }catch (Exception e){
                                                e.printStackTrace();
                                            }
                                        }
                                    }else{
                                        try {
                                            //（2）显示弹窗并且当关闭弹窗后跳到指定页面
                                            response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
                                            response.getWriter().print("<html><body><script type='text/javascript'>alert('文档不存在或下载地址错误！');window.location='/knowledge/download';</script></body></html>");
                                            //response.getWriter().close();
                                            response.getWriter().flush();
                                        }catch (Exception e){
                                            e.printStackTrace();
                                        }
                                    }
                                }else{
                                    try {
                                        response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
                                        response.getWriter().print("<html><body><script type='text/javascript'>alert('下载地址错误');window.location='/knowledge/download';</script></body></html>");
                                        response.getWriter().flush();
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                            }else{
                                try {
                                    response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
                                    response.getWriter().print("<html><body><script type='text/javascript'>alert('您的下载权限已过期或还未开始。开始下载时间："+ DateFormat.getStrDate(customer.getDownloadBDate())+"结束下载时间："+DateFormat.getStrDate(customer.getDownloadEDate())+"');window.location='/knowledge/download';</script></body></html>");
                                    response.getWriter().flush();
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                            }
                        }else{
                            try {
                                response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
                                response.getWriter().print("<html><body><script type='text/javascript'>alert('您无权下载此文档，请联系管理员');window.location='/knowledge/download';</script></body></html>");
                                response.getWriter().flush();
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }else if("0".equals(privType)){ //浏览权限
                        try {
                            response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
                            response.getWriter().print("<html><body><script type='text/javascript'>alert('您无权下载此文档，请联系管理员');window.location='/knowledge/download';</script></body></html>");
                            response.getWriter().flush();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }else{
                        try {
                            response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
                            response.getWriter().print("<html><body><script type='text/javascript'>alert('您无权下载此文档，请联系管理员');window.location='/knowledge/download';</script></body></html>");
                            response.getWriter().flush();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }else{
                    try {
                        response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
                        response.getWriter().print("<html><body><script type='text/javascript'>alert('您无权下载此文档，请联系管理员');window.location='/knowledge/download';</script></body></html>");
                        response.getWriter().flush();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }else{
                try {
                    response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
                    response.getWriter().print("<html><body><script type='text/javascript'>alert('用户不存在，请联系管理员');window.location='/knowledge/download';</script></body></html>");
                    response.getWriter().flush();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }else{
            try {
                response.setContentType("text/html; charset=UTF-8");//注意text/html，和application/html
                response.getWriter().print("<html><body><script type='text/javascript'>alert('登录过期，请重新登录');window.location='/knowledge/download';</script></body></html>");
                response.getWriter().flush();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public LimsJson lookFile(HttpServletRequest request,Integer docId){
        LimsJson limsJson = new LimsJson<>(1, "未知错误");
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        if(users!=null){
            KnowledgeCustomer customer = knowledgeCustomerMapper.selectByUserId(users.getUserId());
            if(customer!=null){
                String privType = customer.getPrivType(); //获取该客户下载权限
                String custColumns = customer.getColumnId(); //获取该客户栏目类别权限
                if(!StringUtils.checkNull(privType)&&!StringUtils.checkNull(custColumns)){
                    if("1".equals(privType)){ //浏览时有下载权限
                        boolean downFlag = true;
                        if(customer.getDownloadBDate()!=null&&customer.getDownloadEDate()!=null){
                            if(knowUtil==null){
                                knowUtil = new KnowledgeUtil();
                            }
                            boolean downFlag1 = knowUtil.belongCalendar(new Date(),customer.getDownloadBDate(),customer.getDownloadEDate()); //判断当前时间是否在下载时间内
                            if(downFlag1){
                                if(docId!=null){
                                    KnowledgeDocfile kd = knowledgeDocfileMapper.selectByPrimaryKey(docId);
                                    //KnowledgeDocfile kd = knowledgeDocfileMapper.selectByAddress(key);
                                    if(kd!=null){
                                        if(kd.getColumnId()!=null){
                                            //此处验证该文档的栏目类别是否在客户栏目类别中
                                            boolean columnTypeFlag = isHaveColumn(custColumns,kd.getColumnId());
                                            if(columnTypeFlag){
                                                downFlag = false;
                                                String attachId = kd.getAttachmentId();
                                                LimsJson filJson = equipmentService.selectAttchUrl(attachId,request,"knowledge");
                                                //文档查看时，新增下载记录
                                                KnowledgeCustomerUselog kcu = new KnowledgeCustomerUselog();
                                                kcu.setUserId(users.getUserId());
                                                kcu.setUseType("0");
                                                kcu.setDocfileId(docId);
                                                kcu.setUseTime(new Date());
                                                kcu.setCustomerName(customer.getCompanyName());
                                                kcu.setDocfileName(kd.getDocfileName());
                                                kcu.setDocfileNo(kd.getDocfileNo());
                                                knowledgeCustomerUselogMapper.insertSelective(kcu);
                                                limsJson.setObj(filJson.getObject());
                                                limsJson.setCode(0);
                                            }else{
                                                limsJson.setMsg("您无权查看此类型文档");
                                            }
                                        }else{
                                            limsJson.setMsg("文档类型错误");
                                        }
                                    }else{
                                        limsJson.setMsg("文档不存在或浏览地址错误");
                                    }
                                }else{
                                    limsJson.setMsg("浏览地址错误");
                                }
                            }else{
                                limsJson.setMsg("您的浏览权限已过期或还未开始。开始浏览时间："+ DateFormat.getStrDate(customer.getBrowseBDate())+"结束浏览时间："+DateFormat.getStrDate(customer.getBrowseEDate()));
                            }
                        }
                        if(downFlag){
                            //此处验证权限过期问题
                            if(customer.getBrowseBDate()!=null&&customer.getBrowseEDate()!=null){
                                if(knowUtil==null){
                                    knowUtil = new KnowledgeUtil();
                                }
                                boolean downFlag2 = knowUtil.belongCalendar(new Date(),customer.getBrowseBDate(),customer.getBrowseEDate()); //判断当前时间是否在浏览时间内
                                if(downFlag2){
                                    if(docId!=null){
                                        KnowledgeDocfile kd = knowledgeDocfileMapper.selectByPrimaryKey(docId);
//                                        KnowledgeDocfile kd = knowledgeDocfileMapper.selectByAddress(key);
                                        if(kd!=null){
                                            String attachId = kd.getAttachmentId();
                                            LimsJson filJson = equipmentService.selectAttchUrl(attachId,request,"knowledge");
                                            //文档查看时，新增下载记录
                                            KnowledgeCustomerUselog kcu = new KnowledgeCustomerUselog();
                                            kcu.setUserId(users.getUserId());
                                            kcu.setUseType("0");
                                            kcu.setDocfileId(docId);
                                            kcu.setUseTime(new Date());
                                            kcu.setCustomerName(customer.getCompanyName());
                                            kcu.setDocfileName(kd.getDocfileName());
                                            kcu.setDocfileNo(kd.getDocfileNo());
                                            knowledgeCustomerUselogMapper.insertSelective(kcu);
                                            limsJson.setObj(filJson.getObject());
                                            limsJson.setCode(0);
                                        }else{
                                            limsJson.setMsg("文档不存在或浏览地址错误");
                                        }
                                    }else{
                                        limsJson.setMsg("浏览地址错误");
                                    }
                                }else{
                                    limsJson.setMsg("您的浏览权限已过期或还未开始。开始浏览时间："+ DateFormat.getStrDate(customer.getBrowseBDate())+"结束浏览时间："+DateFormat.getStrDate(customer.getBrowseEDate()));
                                }
                            }else{
                                limsJson.setMsg("您无权查看此文档，请联系管理员");
                            }
                        }
                    }else if("0".equals(privType)){ //下载和浏览权限,能下载就可以浏览
                        //此处验证权限过期问题
                        if(customer.getBrowseBDate()!=null&&customer.getBrowseEDate()!=null){
                            if(knowUtil==null){
                                knowUtil = new KnowledgeUtil();
                            }
                            boolean downFlag = knowUtil.belongCalendar(new Date(),customer.getBrowseBDate(),customer.getBrowseEDate()); //判断当前时间是否在下载时间内
                            if(downFlag){
                                if(docId!=null){
                                    KnowledgeDocfile kd = knowledgeDocfileMapper.selectByPrimaryKey(docId);
                                    //KnowledgeDocfile kd = knowledgeDocfileMapper.selectByAddress(key);
                                    if(kd!=null){
                                        if(kd.getColumnId()!=null){
                                            boolean columnTypeFlag = isHaveColumn(custColumns,kd.getColumnId());
                                            if(columnTypeFlag){
                                                String attachId = kd.getAttachmentId();
                                                //文档查看时，新增下载记录
                                                KnowledgeCustomerUselog kcu = new KnowledgeCustomerUselog();
                                                kcu.setUserId(users.getUserId());
                                                kcu.setUseType("0");
                                                kcu.setDocfileId(docId);
                                                kcu.setUseTime(new Date());
                                                kcu.setCustomerName(customer.getCompanyName());
                                                kcu.setDocfileName(kd.getDocfileName());
                                                kcu.setDocfileNo(kd.getDocfileNo());
                                                knowledgeCustomerUselogMapper.insertSelective(kcu);
                                                LimsJson filJson = equipmentService.selectAttchUrl(attachId,request,"knowledge");
                                                limsJson.setObj(filJson.getObject());
                                                limsJson.setCode(0);
                                            }else{
                                                limsJson.setMsg("您无权查看此类型文档");
                                            }
                                        }else{
                                            limsJson.setMsg("文档类型错误");
                                        }
                                    }else{
                                        limsJson.setMsg("文档不存在或浏览地址错误");
                                    }
                                }else{
                                    limsJson.setMsg("浏览地址错误");
                                }
                            }else{
                                limsJson.setMsg("您的浏览权限已过期或还未开始。开始浏览时间："+ DateFormat.getStrDate(customer.getBrowseBDate())+"结束浏览时间："+DateFormat.getStrDate(customer.getBrowseEDate()));
                            }
                        }else{
                            limsJson.setMsg("您无权查看此文档，请联系管理员");
                        }
                    }else{
                        limsJson.setMsg("您无权查看此文档，请联系管理员");
                    }
                }else{
                    limsJson.setMsg("您无权查看此文档，请联系管理员");
                }
            }else{
                limsJson.setMsg("用户不存在，请联系管理员");
            }
        }else{
            limsJson.setCode(3);
            limsJson.setMsg("登录过期，请重新登录");
        }
        return limsJson;
    }


    public LimsJson getCurrentPriv(HttpServletRequest request, KnowledgeDocfile docfile,Integer page,Integer limit){
        LimsJson limsJson = new LimsJson(4,"您无权查看或下载");
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        if(users!=null){
            KnowledgeCustomer customer = knowledgeCustomerMapper.selectByUserId(users.getUserId());
            if(customer!=null){
                //if(!StringUtils.checkNull(key)){
                    String privType = customer.getPrivType(); //获取该客户下载权限
                    String custColumn =customer.getColumnId();
                    if(!StringUtils.checkNull(privType)&&!StringUtils.checkNull(custColumn)){
                        if("1".equals(privType)){ //下载和浏览权限
                            boolean flag = true; //如果下载权限验证通过了，则浏览权限不需要再验证
                            //此处验证下载权限过期问题
                            if(customer.getDownloadBDate()!=null&&customer.getDownloadEDate()!=null){
                                if(knowUtil==null){
                                    knowUtil = new KnowledgeUtil();
                                }
                                //判断下载时间
                                boolean downFlag1 = knowUtil.belongCalendar(new Date(),customer.getDownloadBDate(),customer.getDownloadEDate()); //判断当前时间是否在下载时间内
                                if(downFlag1){
                                    //KnowledgeDocfile kd = knowledgeDocfileMapper.selectByAddress(key);
                                    String[] coluArr = custColumn.split(",");
                                    String isSysCode = "";
                                    for(String str : coluArr){
                                        isSysCode+="false,";
                                    }
                                    if(docfile==null){
                                        docfile = new KnowledgeDocfile();
                                    }
                                    if(!StringUtils.checkNull(docfile.getColumnId())){ //不等于null是前端搜索,此时过滤一下，只能用客户权限中的栏目类别搜索
                                        String colu = docfile.getColumnId();
                                        String[] colArr = colu.split(",");
                                        String useColumn="";
                                        String useSyscode="";
                                        for(String str : colArr){
                                            if(isHaveColumn(custColumn,str)){
                                                useColumn+=str+",";
                                                useSyscode+="false,";
                                            }
                                        }
                                        docfile.setColumnId(useColumn);
                                        docfile.setIsSysCode(useSyscode);
                                    }else{
                                        docfile.setColumnId(custColumn);
                                        docfile.setIsSysCode(isSysCode);
                                    }
                                    if(!StringUtils.checkNull(docfile.getColumnId())){
                                        LimsJson serchLimsJson = subscribeService.search(request,docfile,page,limit);
                                        List<KnowledgeDocfile> lkd = serchLimsJson.getData();
                                        for(KnowledgeDocfile ld : lkd){
                                            ld.setCode(1);
                                        }
                                        //List<KnowledgeDocfile> kd = knowledgeDocfileMapper.selectByColumnIds(custColumn.split(","));
                                        //limsJson.setData(kd);
                                        limsJson.setData(lkd);
                                        limsJson.setCount(serchLimsJson.getCount());
                                        limsJson.setObj(customer);
                                        flag = false;
                                        limsJson.setMsg("");
                                        limsJson.setCode(0);
                                    }
                                }
                            }
                            if(flag){ //当客户有下载权限但是下载时间已结束或还未开始，判断有没有查看权限
                                //此处验证浏览权限问题
                                if(customer.getBrowseBDate()!=null&&customer.getBrowseEDate()!=null){
                                    if(knowUtil==null){
                                        knowUtil = new KnowledgeUtil();
                                    }
                                    //判断下载时间
                                    boolean downFlag1 = knowUtil.belongCalendar(new Date(),customer.getBrowseBDate(),customer.getBrowseEDate()); //判断当前时间是否在下载时间内
                                    if(downFlag1){
                                        //List<KnowledgeDocfile> kd = knowledgeDocfileMapper.selectByColumnIds(custColumn.split(","));
//                                        KnowledgeDocfile kd = knowledgeDocfileMapper.selectByAddress(key);
//                                        kd = setDocFile(kd);
//                                        List<KnowledgeDocfile> list = new ArrayList<KnowledgeDocfile>();
//                                        list.add(kd);
                                        String[] coluArr = custColumn.split(",");
                                        String isSysCode = "";
                                        for(String str : coluArr){
                                            isSysCode+="false,";
                                        }
                                        if(docfile==null){
                                            docfile = new KnowledgeDocfile();
                                        }
                                        if(!StringUtils.checkNull(docfile.getColumnId())){ //不等于null是前端搜索,此时过滤一下，只能用客户权限中的栏目类别搜索
                                            String colu = docfile.getColumnId();
                                            String[] colArr = colu.split(",");
                                            String useColumn="";
                                            String useSyscode="";
                                            for(String str : colArr){
                                                if(isHaveColumn(custColumn,str)){
                                                    useColumn+=str+",";
                                                    useSyscode+="false,";
                                                }
                                            }
                                            docfile.setColumnId(useColumn);
                                            docfile.setIsSysCode(useSyscode);
                                        }else{
                                            docfile.setColumnId(custColumn);
                                            docfile.setIsSysCode(isSysCode);
                                        }
                                        if(!StringUtils.checkNull(docfile.getColumnId())){
                                            LimsJson serchLimsJson = subscribeService.search(request,docfile,page,limit);
                                            List<KnowledgeDocfile> lkd = serchLimsJson.getData();
                                            for(KnowledgeDocfile ld : lkd){
                                                ld.setCode(0);
                                            }
                                            limsJson.setObj(customer);
                                            limsJson.setData(lkd);
                                            limsJson.setCount(serchLimsJson.getCount());
                                            limsJson.setMsg("");
                                            limsJson.setCode(0);
                                        }
                                    }
                                }
                            }
                        }else if("0".equals(privType)){ //浏览权限
                            //此处验证权限过期问题
                            if(customer.getBrowseBDate()!=null&&customer.getBrowseEDate()!=null){
                                if(knowUtil==null){
                                    knowUtil = new KnowledgeUtil();
                                }
                                boolean downFlag = knowUtil.belongCalendar(new Date(),customer.getBrowseBDate(),customer.getBrowseEDate()); //判断当前时间是否在下载时间内
                                if(downFlag){
//                                    KnowledgeDocfile kd = knowledgeDocfileMapper.selectByAddress(key);
//                                    kd = setDocFile(kd);
//                                    List<KnowledgeDocfile> list = new ArrayList<KnowledgeDocfile>();
//                                    list.add(kd);
                                    String[] coluArr = custColumn.split(",");
                                    String isSysCode = "";
                                    for(String str : coluArr){
                                        isSysCode+="false,";
                                    }
                                    if(docfile==null){
                                        docfile = new KnowledgeDocfile();
                                    }
                                    if(!StringUtils.checkNull(docfile.getColumnId())){ //不等于null是前端搜索,此时过滤一下，只能用客户权限中的栏目类别搜索
                                        String colu = docfile.getColumnId();
                                        String[] colArr = colu.split(",");
                                        String useColumn="";
                                        String useSyscode="";
                                        for(String str : colArr){
                                            if(isHaveColumn(custColumn,str)){
                                                useColumn+=str+",";
                                                useSyscode+="false,";
                                            }
                                        }
                                        docfile.setColumnId(useColumn);
                                        docfile.setIsSysCode(useSyscode);
                                    }else{
                                        docfile.setColumnId(custColumn);
                                        docfile.setIsSysCode(isSysCode);
                                    }
                                    if(!StringUtils.checkNull(docfile.getColumnId())){
                                        LimsJson serchLimsJson = subscribeService.search(request,docfile,page,limit);
                                        List<KnowledgeDocfile> lkd = serchLimsJson.getData();
                                        for(KnowledgeDocfile ld : lkd){
                                            ld.setCode(0);
                                        }
                                        limsJson.setData(lkd);
//                                    List<KnowledgeDocfile> kd = knowledgeDocfileMapper.selectByColumnIds(custColumn.split(","));
//                                    limsJson.setData(kd);
                                        limsJson.setCode(0);
                                        limsJson.setMsg("");
                                        limsJson.setCount(serchLimsJson.getCount());
                                        limsJson.setObj(customer);
                                    }
                                }else{
                                    limsJson.setMsg("您的浏览权限已过期或还未开始。开始浏览时间："+ DateFormat.getStrDate(customer.getBrowseBDate())+"结束浏览时间："+DateFormat.getStrDate(customer.getBrowseEDate()));
                                }
                            }else{
                                limsJson.setMsg("您的浏览权限错误，请联系管理员");
                            }
                        }else{
                            limsJson.setCode(0);
                            limsJson.setMsg("您无权查看或下载");
                        }
                    }else{
                        limsJson.setMsg("您无权查看或下载");
                    }
//                }else{
//                    limsJson.setMsg("下载地址错误");
//                }
            }else{
                limsJson.setMsg("用户不存在");
            }
        }else{
            limsJson.setCode(0);//登录过期
        }
        return limsJson;
    }

    /**
     * 判断客户栏目类别是否在文档类别中
     * @param custColumns 客户可下载查看的栏目类别
     * @param docColumns 文档的栏目类别
     *                  1.根据custColumns 查出该客户所有栏目类别权限，查出的是个map
     *                  2.循环docColumns 从map中拿 有就返回true
     * @return
     */
    private boolean isHaveColumn(String custColumns,String docColumns){
        if(!StringUtils.checkNull(custColumns)&&!StringUtils.checkNull(docColumns)){
            Map<String,String> custColumnMap = new HashMap<>(); //用来记录客户所有权限
            String[] custColArr = custColumns.split(",");
            for(int i=0;i<custColArr.length;i++){
                String custCol = custColArr[i];
                if(!StringUtils.checkNull(custCol)){
                    custColumnMap.put(custCol,custCol); //把他本身放进map
                    List<KnowledgeColumn> columnList = knowledgeColumnMapper.getAllChileByColumnId(custCol); //查询该类型下所有子集，包括子集的子集
                    for(KnowledgeColumn kc : columnList){
                        custColumnMap.put(String.valueOf(kc.getColumnId()),String.valueOf(kc.getColumnId())); //把每一个子集放进map
                    }
                }
            }
            String[] docColArr = docColumns.split(",");
            for(String docCol : docColArr){
                if(custColumnMap.get(docCol)!=null){
                    return true;
                }
            }
        }
        return false;
    }

    private KnowledgeDocfile setDocFile(KnowledgeDocfile docfile){
        if(!StringUtils.checkNull(docfile.getColumnId())){
            String[] str = (docfile.getColumnId()).split(",");
            // 通过子节点查询该子节点之上的多有节点
            String columnName = "";
            for (String s : str) {
                if(!StringUtils.checkNull(s)){
                    KnowledgeColumn knowledgeColumn;
                    List<String> textList = new ArrayList<>();
                    boolean flag = true;
                    knowledgeColumn = knowledgeColumnMapper.selectByPrimaryKey(Integer.valueOf(s));
                    if(knowledgeColumn!=null){
                        columnName+=knowledgeColumn.getColumnName()+",";
                    }
                }
            }
            if(columnName.endsWith(",")){
                columnName = columnName.substring(0,columnName.length()-1);
            }
            docfile.setColumnName(columnName);
        }
        return docfile;
    }

    @Override
    public LimsJson getCustomerTree(HttpServletRequest request) {
        LimsJson limsJson = new LimsJson<>(1, "查询失败");
        List<Integer> dispIdList = new ArrayList<>();//定义前端不能选择的数据的id
        List<KnowledgeColumn> resultList = new ArrayList<>(); //定义返回值
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        if(users!=null){
            KnowledgeCustomer customer = knowledgeCustomerMapper.selectByUserId(users.getUserId());
            if(customer!=null){
                if(!StringUtils.checkNull(customer.getColumnId())){
                    resultList = getAll(customer.getColumnId());
                    if(resultList!=null&&resultList.size()>0){
                        limsJson.setCode(0);
                        limsJson.setData(resultList);
                        limsJson.setObj(dispIdList);
                    }else{
                        limsJson.setCode(0);
                        limsJson.setMsg("暂无数据");
                    }
                }else{
                    limsJson.setMsg("您没有知识类别权限");
                }
            }else{
                limsJson.setMsg("客户信息不存在，请联系管理员");
            }
        }else{
            limsJson.setMsg("角色错误，请联系管理员");
        }
        return limsJson;
    }

    private List<KnowledgeColumn> getAll(String columnIds){
        List<KnowledgeColumn> resultList = new ArrayList<>();
        if(!StringUtils.checkNull(columnIds)){
            String[] columnArr = columnIds.split(",");
            Map<Integer,KnowledgeColumn> haveMap = new HashMap<>();
            for(String colId : columnArr){
                if(!StringUtils.checkNull(colId)){
                    KnowledgeColumn kc =  knowledgeColumnMapper.selectByPrimaryKey(Integer.valueOf(colId));
                    if(kc!=null){
                        kc.setId(kc.getColumnId());
                        kc.setLabel(kc.getColumnName());
                        kc.setSysCode(false);  //标识是否是sysCode的数据
                        kc.setName(kc.getColumnName());
                        haveMap.put(kc.getColumnId(),kc);
                        List<KnowledgeColumn> childList = knowledgeColumnMapper.getAllChileByColumnId(String.valueOf(kc.getColumnId()));
                        if(childList!=null&&childList.size()>0){
                            for(KnowledgeColumn child : childList){
                                child.setId(child.getColumnId());
                                child.setLabel(child.getColumnName());
                                child.setSysCode(false);  //标识是否是sysCode的数据
                                child.setName(child.getColumnName());
                                haveMap.put(child.getColumnId(),child);
                            }
                        }
                    }
                }
            }
            List<Integer> removeIdList = new ArrayList<>();
            //Map<Integer,KnowledgeColumn> kcMap = new HashMap<>();
            for(Map.Entry map : haveMap.entrySet()){
                Integer key = (Integer)map.getKey();
                KnowledgeColumn kc = (KnowledgeColumn)map.getValue();
//                if(kc.getParentColumnId()==0){
//                    haveMap.put(key,kc);
//                }else{
                    if(haveMap.get(kc.getParentColumnId())!=null){
                        removeIdList.add(key);
                        KnowledgeColumn parentKc = haveMap.get(kc.getParentColumnId());
                        List<KnowledgeColumn> childen = parentKc.getChildren();
                        if(childen==null){
                            childen = new ArrayList<>();
                            childen.add(kc);
                            parentKc.setChildren(childen);
                        }else{
                            parentKc.getChildren().add(kc);
                        }
                    }
//                    else{
//                        haveMap.put(key,kc);
//                    }
                //}
            }
            for(Integer in : removeIdList){
                haveMap.remove(in);
            }
            for(Map.Entry map : haveMap.entrySet()){
                resultList.add((KnowledgeColumn)map.getValue());
            }
        }
        return resultList;
    }
}
